package com.example.port.Controller;

import com.example.port.dto.ApiResponse;
import com.example.port.entity.FeeRule;
import com.example.port.exception.ServiceException;
import com.example.port.service.FeeRuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/fee-rules")
public class FeeRuleController {
    
    private static final Logger logger = LoggerFactory.getLogger(FeeRuleController.class);
    
    private final FeeRuleService feeRuleService;
    
    @Autowired
    public FeeRuleController(FeeRuleService feeRuleService) {
        this.feeRuleService = feeRuleService;
    }
    
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<Integer> createFeeRule(@RequestBody FeeRule rule) {
        int result = feeRuleService.insertFeeRule(rule);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "创建费用规则失败");
    }
    
    @GetMapping
    public ApiResponse<List<FeeRule>> getAllFeeRules() {
        List<FeeRule> feeRules = feeRuleService.getAllFeeRules();
        return ApiResponse.success(feeRules);
    }
    
    @DeleteMapping("/{ruleId}")
    public ApiResponse<Integer> deleteFeeRule(@PathVariable Integer ruleId) {
        logger.info("接收到删除费用规则请求, ID: {}", ruleId);
        try {
            // 直接调用服务层的删除方法，服务层会负责检查规则是否被使用
            int result = feeRuleService.deleteFeeRule(ruleId);
            if (result > 0) {
                logger.info("费用规则ID: {} 删除成功", ruleId);
                return ApiResponse.success(result);
            }
            logger.warn("费用规则ID: {} 删除失败，可能不存在", ruleId);
            return ApiResponse.error(404, "删除费用规则失败，可能不存在该规则");
        } catch (ServiceException e) {
            logger.error("删除费用规则时发生服务异常: {}", e.getMessage());
            return ApiResponse.error(400, e.getMessage());
        } catch (Exception e) {
            logger.error("删除费用规则时发生未知异常", e);
            return ApiResponse.error(500, "删除费用规则失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{ruleId}")
    public ApiResponse<Integer> updateFeeRule(@PathVariable Integer ruleId, @RequestBody FeeRule rule) {
        rule.setRuleId(ruleId);
        int result = feeRuleService.updateFeeRule(rule);
        if (result > 0) {
            return ApiResponse.success(result);
        }
        return ApiResponse.error(500, "更新费用规则失败");
    }
} 
